<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="Hadd('0','1')"
          >添加权限</el-button>
        </div>
        <el-table row-key="id" :data="data" border>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button
                v-if="row.type === 1"
                type="text"
                @click="Hadd(row.id,2)"
              >添加</el-button>
              <el-button type="text" @click="Hput(row)">编辑</el-button>
              <el-button v-if="row.children.length === 0" type="text" @click="Hdel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :title="isEdit ?'编辑' :'添加'"
        :visible.sync="showDialog"
        @close="reset"
      >
        <!-- 表单内容 -->
        <el-form ref="refForm" :rules="rules" :model="formData" label-width="100px">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="Hsubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { tranDataToTree } from '@/utils/index'
import { getPermissionList, addPermission, updatePermission, delPermission } from '@/api/permisson'
export default {
  data() {
    // 自定义校验code
    const validCode = (rule, value, callback) => {
      // 添加状态code
      let isCode = this.filterData.map(item => item.code)
      // console.log('添加状态isCode', isCode)
      if (this.isEdit) {
        // 编辑状态的 code
        isCode = this.filterData.filter(item => item.id !== this.formData.id).map(item => item.code)
        // console.log('编辑状态isCode', isCode)
      }
      if (isCode.includes(value)) {
        callback(new Error(`不可存在相同${value}存在,请重新输入`))
      } else {
        callback()
      }
    }
    // 自定义校验name
    const validName = (rule, value, callback) => {
      // 添加状态Name
      let isName = this.filterData.filter(item => item.pid === this.formData.pid).map(item => item.name)
      // console.log('添加状态isName', isName)
      if (this.isEdit) {
        // 编辑状态的 Name
        // 遍历所有 pid 找到当前被点击元素 获得被点击元素的pid
        const pid = this.filterData.find(item => item.pid === this.formData.pid).pid
        // 判断所有pid只要===被点击元素的pid的数组     在吧当前被点击的元素去除掉  在取name
        isName = this.filterData.filter(item => item.pid === pid).filter(item => item.id !== this.formData.id).map(item => item.name)
        // console.log('pid', pid)
        // console.log('编辑状态isName', isName)
      }
      if (isName.includes(value)) {
        callback(new Error(`不可存在相同${value}存在,请重新输入`))
      } else {
        callback()
      }
    }
    return {
      data: [], // 保存权限列表数据
      showDialog: false,
      isEdit: false, // 控制弹层状态
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入权限描述', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ]
      },
      filterData: [] // 保存权限数据用来做表单的验证
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        // console.log('getPermissionList', res)
        // 保存数据
        if (res.code !== 10000) return
        // 获取扁平的数据做表单自定义校验
        this.filterData = res.data.map(item => {
          return { id: item.id, name: item.name, code: item.code, pid: item.pid }
        })
        // 把获得的扁平数据 转化树形数据
        this.data = tranDataToTree(res.data)
      } catch (err) {
        console.log('getPermissionList', err)
      }
    },
    // 弹层关闭清空表单数据
    reset() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
    },
    // 点击了确定
    Hsubmit() {
      this.$refs.refForm.validate((valid) => {
        if (!valid) return // 校验失败
        // 校验成功
        this.isEdit ? this.putPermission() : this.newData()
      })
    },
    // 点击了添加||添加权限
    Hadd(id, type) {
      this.isEdit = false // 修改弹层的状态
      this.formData.pid = id
      this.formData.type = type
      this.showDialog = true
    },
    // 点击了编辑
    Hput(row) {
      this.isEdit = true
      this.showDialog = true
      this.formData = { ...row }
    },
    // 新增权限
    async newData() {
      try {
        const res = await addPermission(this.formData)
        // console.log('addPermission', res)
        // 保存数据
        if (res.code !== 10000) return
        this.$message.success(res.message)
        this.loadPermissionList()
        this.showDialog = false
      } catch (err) {
        console.log('addPermission', err)
      }
    },
    // 修改权限
    async putPermission() {
      try {
        const res = await updatePermission(this.formData)
        // console.log('updatePermission', res)
        // 保存数据
        if (res.code !== 10000) return
        this.$message.success(res.message)
        this.loadPermissionList()
        this.showDialog = false
      } catch (err) {
        console.log('updatePermission', err)
      }
    },
    // /点击了删除
    Hdel(id) {
      this.$confirm('你点击了删除,是否继续?', '提示').then(async() => {
        try {
          const res = await delPermission(id)
          // console.log('delPermission', res)
          // 保存数据
          if (res.code !== 10000) return
          this.$message.success(res.message)
          this.loadPermissionList()
        } catch (err) {
          console.log('delPermission', err)
        }
      }).catch(err => console.log(err))
    }

  }
}
</script>
